package com.sboot.shiro.common.shiro;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.sboot.shiro.biz.sys.user.po.SysPermission;
import com.sboot.shiro.biz.sys.user.po.SysUser;
import com.sboot.shiro.biz.sys.user.service.SysPermissionService;
import com.sboot.shiro.biz.sys.user.service.SysUserService;
import com.sboot.shiro.common.dict.UserStateEnum;

public class AuthRealm extends AuthorizingRealm {

	@Autowired
	private SysUserService userService;
	
	@Autowired
	private SysPermissionService permissionService;

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SysUser user = (SysUser)principals.fromRealm(this.getClass().getName()).iterator().next();
		Set<SysPermission> permissions = permissionService.getPermissionsByUserId(user.getId());
		List<String> pers = new ArrayList<String>();
		permissions.forEach(per -> {
			pers.add(per.getCode());
		});
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addStringPermissions(pers);
		return simpleAuthorizationInfo;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken uToken = (UsernamePasswordToken) token;
		String userName = uToken.getUsername();
		SysUser user = userService.getUserByLoginName(userName);
		if (user==null) {
			throw new AccountException("账号或密码不正确");
		} else if (UserStateEnum.LOCKED.getCode().equals(user.getState())) {
			throw new DisabledAccountException("账号已被锁定");
		}
		return new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
	}

}
